package org.example;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;

public class HoverLauncher extends JFrame {
    // 窗口展开时的宽度
    private static int EXPANDED_WIDTH = 150;
    // 窗口折叠时的宽度
    private static final int COLLAPSED_WIDTH = 10;
    // 窗口的高度
    private static final int WINDOW_HEIGHT = 400;
    // 鼠标悬停延迟时间
    private static final int HOVER_DELAY = 200;

    // 窗口是否展开
    private boolean isExpanded = true;
    // 启动器项目列表
    private List<LauncherItem> items = new ArrayList<>();
    // 主面板
    private JPanel mainPanel;
    // 鼠标悬停计时器
    private Timer hoverTimer;
    // 配置文件路径
    private String configFile = "launcher_config.json";
    // 右键菜单
    private JPopupMenu contextMenu;
    // 拖动起始位置X坐标
    private int dragStartX;
    // 是否正在拖动
    private boolean isDragging = false;
    // 最小宽度
    private static final int MIN_WIDTH = 100;
    // 最大宽度
    private static final int MAX_WIDTH = 400;
    // 是否锁定展开状态
    private boolean isLocked = false;
    // 锁定按钮
    private JButton lockButton;
    // 最后点击的标签
    private JLabel lastClickedLabel;

    public HoverLauncher() {
        initializeFrame(); // 初始化窗口
        loadConfig(); // 加载配置
        createContextMenu(); // 创建右键菜单
        updateUI(); // 更新UI
        positionWindow(); // 设置窗口位置
    }

    private void initializeFrame() {
        setUndecorated(true); // 无边框
        setAlwaysOnTop(true); // 总在最前
        setType(Type.UTILITY); // 设置窗口类型
        setLayout(new BorderLayout()); // 设置布局

        // 创建主面板
        mainPanel = new JPanel();
        // 设置垂直布局
        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
        // 设置深灰色背景
        mainPanel.setBackground(new Color(43, 43, 43));

        JScrollPane scrollPane = new JScrollPane(mainPanel);
        scrollPane.setBorder(null);
        add(scrollPane, BorderLayout.CENTER);

        // 创建锁定按钮
        lockButton = new JButton("\uD83D\uDD13"); // Unicode for 🔓
        lockButton.setFocusPainted(false);
        lockButton.setPreferredSize(new Dimension(70, 40)); // 增加按钮的大小
        lockButton.setFont(new Font("Dialog", Font.PLAIN, 24)); // 增大字体以适应图标
        lockButton.setBorderPainted(false);
        lockButton.setContentAreaFilled(false); // 如果想要透明背景

        // 添加鼠标监听器来处理悬停事件
        lockButton.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                Timer hoverTimer = new Timer(500, evt -> toggleLock()); // 500毫秒后执行
                hoverTimer.setRepeats(false);
                hoverTimer.start();
            }

            @Override
            public void mouseExited(MouseEvent e) {
                // 如果需要在鼠标离开时执行其他操作，可以在这里添加代码
            }
        });

        // 创建关闭按钮
        JButton closeButton = new JButton("X");
        closeButton.setFocusPainted(false);
        closeButton.setPreferredSize(new Dimension(50, 50)); // 增加按钮的大小
        closeButton.setFont(new Font("Dialog", Font.PLAIN, 18)); // 确保字体大小适合
        closeButton.setBorderPainted(false);
        closeButton.setContentAreaFilled(false);
        closeButton.setForeground(Color.RED);
        closeButton.addActionListener(e -> System.exit(0)); // 点击关闭程序

        // 创建一个面板来放置锁定和关闭按钮
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 5));
        buttonPanel.setBackground(new Color(43, 43, 43));
        buttonPanel.add(lockButton);
        buttonPanel.add(closeButton); // 添加关闭按钮

        // 将按钮面板添加到窗口顶部
        add(buttonPanel, BorderLayout.NORTH);

        // 设置初始大小
        setSize(EXPANDED_WIDTH, 600);
        // 设置窗口位置:
        // 1. 获取屏幕宽度 Toolkit.getDefaultToolkit().getScreenSize().width
        // 2. 将窗口放置在屏幕右侧,距离右边缘 EXPANDED_WIDTH 像素
        // 3. 垂直位置设为距离顶部100像素
        setLocation(Toolkit.getDefaultToolkit().getScreenSize().width - EXPANDED_WIDTH, 100);

        // 为所有相关组件添加鼠标监听器
        MouseAdapter mouseAdapter = new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                // 如果是折叠状态，优先展开
                if (!isExpanded) {
                    expand();
                    return;
                }
                
                // 只在展开状态下才处理调整大小的光标
                if (e.getX() <= 15) {
                    setCursor(Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR));
                }
            }

            @Override
            public void mouseExited(MouseEvent e) {
                // 获取鼠标事件的坐标点
                Point p = e.getPoint();
                // 将组件坐标转换为屏幕坐标
                SwingUtilities.convertPointToScreen(p, (Component)e.getSource());
                // 如果鼠标移出了窗口范围
                if (!getBounds().contains(p)) {
                    // 且当前没有在拖拽状态且窗口未锁定
                    if (!isDragging && !isLocked) {
                        // 折叠窗口
                        collapse();
                    }
                }
                // 如果没有在拖拽状态
                if (!isDragging) {
                    // 恢复默认鼠标指针
                    setCursor(Cursor.getDefaultCursor());
                }
            }

            @Override
            public void mousePressed(MouseEvent e) {
                if (e.getX() <= 15) {
                    isDragging = true;
                    dragStartX = e.getXOnScreen();
                    setCursor(Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR));
                }
            }

            @Override
            public void mouseReleased(MouseEvent e) {
                isDragging = false;
                setCursor(Cursor.getDefaultCursor());
                if (isExpanded) {
                    EXPANDED_WIDTH = getWidth();
                }
            }
        };

        // 为主窗口添加监听器
        addMouseListener(mouseAdapter);

        // 为滚动面板添加监听器
        scrollPane.addMouseListener(mouseAdapter);

        // 为主面板添加监听器
        mainPanel.addMouseListener(mouseAdapter);

        // 添加鼠标拖动监听器
        addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseDragged(MouseEvent e) {
                if (isDragging) {
                    int draggedWidth = getWidth() + (dragStartX - e.getXOnScreen());
                    // 限制宽度在合理范围内
                    draggedWidth = Math.max(MIN_WIDTH, Math.min(MAX_WIDTH, draggedWidth));
                    
                    int screenWidth = Toolkit.getDefaultToolkit().getScreenSize().width;
                    setSize(draggedWidth, getHeight());
                    setLocation(screenWidth - draggedWidth, getY());
                    
                    dragStartX = e.getXOnScreen();
                    revalidate();
                    repaint();
                }
            }

            @Override
            public void mouseMoved(MouseEvent e) {
                if (isExpanded && e.getX() <= 15) {
                    setCursor(Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR));
                } else {
                    setCursor(Cursor.getDefaultCursor());
                }
            }
        });

        // 添加拖拽支持
        mainPanel.setTransferHandler(new TransferHandler() {
            @Override
            public boolean canImport(TransferSupport support) {
                return support.isDataFlavorSupported(DataFlavor.javaFileListFlavor);
            }

            @Override
            public boolean importData(TransferSupport support) {
                if (!canImport(support)) {
                    return false;
                }

                try {
                    Transferable transferable = support.getTransferable();
                    List<File> files = (List<File>) transferable.getTransferData(DataFlavor.javaFileListFlavor);
                    
                    for (File file : files) {
                        addItem(file.getName(), file.getAbsolutePath());
                    }
                    return true;
                } catch (Exception e) {
                    e.printStackTrace();
                    return false;
                }
            }
        });
    }

    private void createContextMenu() {
        contextMenu = new JPopupMenu();
        JMenu addMenu = new JMenu("添加项目");
        JMenuItem addFile = new JMenuItem("添加文件");
        JMenuItem addFolder = new JMenuItem("添加文件夹");
        JMenuItem deleteItem = new JMenuItem("删除项目");

        addFile.addActionListener(e -> addFile());
        addFolder.addActionListener(e -> addFolder());
        deleteItem.addActionListener(e -> deleteCurrentItem());

        addMenu.add(addFile);
        addMenu.add(addFolder);
        contextMenu.add(addMenu);
        contextMenu.addSeparator();
        contextMenu.add(deleteItem);

        // 添加右键菜单监听
        mainPanel.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                if (SwingUtilities.isRightMouseButton(e)) {
                    contextMenu.show(e.getComponent(), e.getX(), e.getY());
                }
            }
        });
    }

    private void addFile() {
        JFileChooser fileChooser = new JFileChooser();
        if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            File file = fileChooser.getSelectedFile();
            addItem(file.getName(), file.getAbsolutePath());
        }
    }

    private void addFolder() {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            File folder = fileChooser.getSelectedFile();
            addItem(folder.getName(), folder.getAbsolutePath());
        }
    }

    private void addItem(String name, String path) {
        items.add(new LauncherItem(name, path));
        saveConfig();
        updateUI();
    }

    private void updateUI() {
        mainPanel.removeAll();

        for (LauncherItem item : items) {
            JLabel label = createItemLabel(item);
            mainPanel.add(label);
        }

        mainPanel.revalidate();
        mainPanel.repaint();
    }

    private JLabel createItemLabel(LauncherItem item) {
        JLabel label = new JLabel(item.getName());
        label.setForeground(Color.WHITE);
        label.setOpaque(true);
        label.setBackground(new Color(45, 45, 45));
        label.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));

        label.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseEntered(MouseEvent e) {
                label.setBackground(new Color(61, 61, 61));
                if (!isLocked) {
                    if (hoverTimer != null) {
                        hoverTimer.stop();
                    }
                    hoverTimer = new Timer(HOVER_DELAY, evt -> openItem(item.getPath(), label));
                    hoverTimer.setRepeats(false);
                    hoverTimer.start();
                }
            }

            @Override
            public void mouseExited(MouseEvent e) {
                label.setBackground(new Color(45, 45, 45));
                if (hoverTimer != null) {
                    hoverTimer.stop();
                }
            }

            @Override
            public void mousePressed(MouseEvent e) {
                if (SwingUtilities.isRightMouseButton(e)) {
                    lastClickedLabel = label; // 记录最后点击的标签
                    contextMenu.show(label, e.getX(), e.getY());
                }
            }
        });

        return label;
    }

    private void openItem(String path, JLabel label) {
        try {
            File file = new File(path);
            Desktop.getDesktop().open(file);

            // 添加更明显的动态特效：标签闪烁
            Timer blinkTimer = new Timer(200, new ActionListener() {
                private int count = 0;
                private boolean isOriginalColor = true;

                @Override
                public void actionPerformed(ActionEvent e) {
                    if (count < 2) { // 增加闪烁次数
                        label.setBackground(isOriginalColor ? new Color(173, 216, 230) : new Color(45, 45, 45)); // 使用浅蓝色
                        isOriginalColor = !isOriginalColor;
                        count++;
                    } else {
                        ((Timer) e.getSource()).stop();
                        label.setBackground(new Color(45, 45, 45)); // 恢复原始颜色
                    }
                }
            });
            blinkTimer.start();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "无法打开: " + e.getMessage());
        }
    }

    private void expand() {
        if (!isExpanded) {
            System.out.println("Expanding...");
            isExpanded = true;
            int screenWidth = Toolkit.getDefaultToolkit().getScreenSize().width;
            setSize(EXPANDED_WIDTH, getHeight());
            setLocation(screenWidth - EXPANDED_WIDTH, getY());
            revalidate();
            repaint();
        }
    }

    private void collapse() {
        if (isExpanded) {
            System.out.println("Collapsing...");
            isExpanded = false;
            int screenWidth = Toolkit.getDefaultToolkit().getScreenSize().width;
            setSize(COLLAPSED_WIDTH, getHeight());
            setLocation(screenWidth - COLLAPSED_WIDTH, getY());
            revalidate();
            repaint();
        }
    }

    // ... 配置文件相方法（loadConfig, saveConfig）...

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception e) {
                e.printStackTrace();
            }
            new HoverLauncher().setVisible(true);
        });
    }

    private void loadConfig() {
        File config = new File(configFile);
        if (config.exists()) {
            try (FileReader reader = new FileReader(config)) {
                JSONParser parser = new JSONParser();
                JSONArray jsonArray = (JSONArray) parser.parse(reader);

                items.clear();
                for (Object obj : jsonArray) {
                    JSONObject jsonObject = (JSONObject) obj;
                    String name = (String) jsonObject.get("name");
                    String path = (String) jsonObject.get("path");
                    items.add(new LauncherItem(name, path));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            // 添加默认项目
            addItem("文档", System.getProperty("user.home") + "/Documents");
            addItem("下载", System.getProperty("user.home") + "/Downloads");
        }
    }

    private void saveConfig() {
        JSONArray jsonArray = new JSONArray();
        for (LauncherItem item : items) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name", item.getName());
            jsonObject.put("path", item.getPath());
            jsonArray.add(jsonObject);
        }

        try (FileWriter writer = new FileWriter(configFile)) {
            writer.write(jsonArray.toJSONString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void positionWindow() {
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        setSize(EXPANDED_WIDTH, WINDOW_HEIGHT);
        setLocation(screenSize.width - EXPANDED_WIDTH, screenSize.height / 3);
    }

    private void deleteCurrentItem() {
        if (lastClickedLabel != null) {
            String name = lastClickedLabel.getText();
            items.removeIf(item -> item.getName().equals(name));
            saveConfig();
            updateUI();
            lastClickedLabel = null; // 重置最后点击的标签
        }
    }

    private void toggleLock() {
        isLocked = !isLocked;
        lockButton.setText(isLocked ? "\uD83D\uDD12" : "\uD83D\uDD13" ); // 🔒 和 🔓
       
    }
}

class LauncherItem {
    private String name;
    private String path;

    public LauncherItem(String name, String path) {
        this.name = name;
        this.path = path;
    }

    public String getName() { return name; }
    public String getPath() { return path; }
}